package com.example.ch04_04;

import java.io.IOException;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class PlayMusic extends Service {
	MediaPlayer player;
	MyReceiver receiver;
	class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String cmd = intent.getExtras().getString(AppConstants.PLAYMUSIC_COMMAND_KEY);
			if(cmd.equals(AppConstants.PLAYMUSIC_COMMAND_PLAY)){
				player.start();
					}else if(cmd.equals(AppConstants.PLAYMUSIC_COMMAND_PAUSE)){
						player.pause();
					}		
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if( player != null){
			player.stop();
		}if( receiver != null){
			player.pause();
		}
		super.onDestroy();
		Log.i ("Service", "Bye Bye Bye!");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.i ("Service", "I am a service!");
		player = MediaPlayer.create(this, R.raw.theshow);
			player.setVolume(1, 1);
		
				try {
					player.prepare();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//player.start();
				if( receiver == null){
					receiver = new MyReceiver();
					this.registerReceiver(receiver, new IntentFilter(AppConstants.PLAYMUSIC_ACTION_KEY));
					
				}
				
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

	
}
